package lsy.redis001.lsyredis001.service.impl;

import lsy.redis001.lsyredis001.entity.Article;
import lsy.redis001.lsyredis001.service.ArticleService;
import lsy.redis001.lsyredis001.service.TagService;
import lsy.redis001.lsyredis001.table.RedisTableConstant;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
public class TagServiceImpl implements TagService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ArticleService articleService;

    @Override
    public void addTag(String tag, Long articleId) {
        redisTemplate.opsForSet().add(RedisTableConstant.getTagPosts(tag),articleId);
    }

    @Override
    public void deleteTag(String tag, Long articleId) {
        redisTemplate.opsForSet().remove(RedisTableConstant.getTagPosts(tag),articleId);
    }

    @Override
    public void deleteTag(String tag) {
        redisTemplate.delete(RedisTableConstant.getTagPosts(tag));
    }

    @Override
    public List<Article> getArticleByTag(String tag) {
        ArrayList<Article> articles = Lists.newArrayList();
        Set<String> members = redisTemplate.opsForSet().members(RedisTableConstant.getTagPosts(tag));
        if(!CollectionUtils.isEmpty(members)){
            for (String articleId:members) {
                Article article = articleService.getOne(Long.valueOf(articleId));
                articles.add(article);
            }
        }
        return articles;
    }

    @Override
    public List<String> getAllTag() {
        List<String> result = new ArrayList<>();
        Set<String> tags = redisTemplate.keys("tag:*:posts");
        if(!CollectionUtils.isEmpty(tags)){
            for (String t: tags) {
                result.add(t.substring(t.indexOf(":"),t.lastIndexOf(":")));
            }
        }
        return result;
    }
}
